import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '购物车',
      theme: ThemeData(
        primarySwatch: Colors.red,
      ),
      home: ShopCarPage(
        arguments: {},
      ),
    );
  }
}

class ShopCarPage extends StatefulWidget {
  final Map arguments;
  const ShopCarPage({Key? key, required this.arguments}) : super(key: key);
  @override
  _ShopCarPageState createState() => _ShopCarPageState(arguments);
}

class _ShopCarPageState extends State<ShopCarPage> {
  final Map arguments;
  bool _selectAll = false;
  List<CartItem> _cartItems = [];

  _ShopCarPageState(this.arguments);
  void loadCartItems() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    // 获取存储的购物车数据（假设是一个 JSON 字符串数组）
    List<String>? cartItemsJsonList = prefs.getStringList('cart');

    if (cartItemsJsonList != null) {
      // 将 List<String> 中的每个 JSON 字符串转换为 Map
      List<CartItem> loadedCartItems = cartItemsJsonList.map((jsonString) {
        Map<String, dynamic> itemMap = json.decode(jsonString);
        return CartItem.fromMap(itemMap);
      }).toList();

      // 更新状态以显示加载的购物车数据
      setState(() {
        _cartItems = loadedCartItems;
      });

      print('${_cartItems}adsadsa');
    }
  }

  @override
  void initState() {
    super.initState();
    loadCartItems();
  }

  @override
  Widget build(BuildContext context) {
    double total = _cartItems
        .where((item) => item.selected)
        .fold(0, (sum, item) => sum + (item.price * item.count));

    int selectedCount = _cartItems.where((item) => item.selected).length;

    return Scaffold(
      appBar: AppBar(title: Text('购物车'), centerTitle: true, actions: [
        TextButton(
          onPressed: () {},
          child: Text('编辑', style: TextStyle(color: Colors.black)),
        )
      ]),
      body: Column(
        children: [
          // 全选栏
          _buildSelectAllRow(),
          Divider(height: 1),

          // 商品列表
          Expanded(
            child: ListView.builder(
              itemCount: _cartItems.length,
              itemBuilder: (context, index) {
                return _buildCartItem(_cartItems[index], index);
              },
            ),
          ),

          // 猜你喜欢标题
          _buildRecommendTitle(),

          // 推荐商品
          _buildRecommendProducts(),

          // 底部结算栏
          _buildCheckoutBar(total, selectedCount),
        ],
      ),
    );
  }

  Widget _buildSelectAllRow() {
    // print("Received Arguments: ${arguments.toString()}");
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
      color: Colors.white,
      child: Row(
        children: [
          Checkbox(
            value: _selectAll,
            shape: CircleBorder(),
            activeColor: Colors.red,
            onChanged: (value) {
              setState(() {
                _selectAll = value!;
                _cartItems = _cartItems.map((item) {
                  return item.copyWith(selected: value);
                }).toList();
              });
            },
          ),
          Text('全选'),
        ],
      ),
    );
  }

  Widget _buildCartItem(CartItem item, int index) {
    return Container(
      margin: EdgeInsets.only(bottom: 8),
      color: Colors.white,
      padding: EdgeInsets.all(16),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Checkbox(
                value: item.selected,
                activeColor: Colors.red,
                shape: CircleBorder(),
                onChanged: (value) {
                    setState(() {
                      _cartItems[index] = item.copyWith(selected: value);
                      _selectAll = _cartItems.every((item) => item.selected);
                    });
                },
              ),
            ],
          ),
          Column(
            children: [
              Image.asset(
                item.img,
                cacheWidth: (MediaQuery.of(context).size.width * 0.35).toInt(),
              ),
            ],
          ),
          Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                item.name,
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 22),
              Row(
                children: [
                  Text('尺码：${item.size}  包数：${item.packages} ✅'),
                  SizedBox(height: 8),
                ],
              ),
              SizedBox(height: 22),
              Row(
                children: [
                  Text('￥${item.price.toStringAsFixed(1)}',
                      style: TextStyle(color: Colors.red, fontSize: 16)),
                //   Spacer(),
                  _buildQuantityControl(item, index),
                ],
              )
            ],
          )
        ],
      ),
    );
  }

  Widget _buildQuantityControl(CartItem item, int index) {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey[300]!),
        borderRadius: BorderRadius.circular(4),
      ),
      child: Row(
        children: [
          IconButton(
            icon: Icon(Icons.remove, size: 18),
            onPressed: () {
              if (item.count > 1) {
                setState(() {
                  _cartItems[index] = item.copyWith(count: item.count - 1);
                });
              }
            },
            padding: EdgeInsets.zero,
            constraints: BoxConstraints(),
          ),
          Container(
            width: 30,
            alignment: Alignment.center,
            child: Text(item.count.toString()),
          ),
          IconButton(
            icon: Icon(Icons.add, size: 18),
            onPressed: () {
              setState(() {
                _cartItems[index] = item.copyWith(count: item.count + 1);
              });
            },
            padding: EdgeInsets.zero,
            constraints: BoxConstraints(),
          ),
        ],
      ),
    );
  }

  Widget _buildRecommendTitle() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
      alignment: Alignment.centerLeft,
      color: Colors.white,
      child: Text('猜你喜欢',
          style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
    );
  }

  Widget _buildRecommendProducts() {
    return GridView.count(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      crossAxisCount: 2,
      childAspectRatio: 0.7,
      padding: EdgeInsets.all(8),
      children: [
        _buildProductItem('帮宝适超薄干爽清新帮纸尿裤S64片(4-Bkg)...', '满400打八折', 19.9),
        _buildProductItem('婴芽（YINGYA）拉拉裤L码2包100片【8-11kg】...', '满400打八折', 19.9),
      ],
    );
  }

  Widget _buildProductItem(String name, String promo, double price) {
    return Card(
      child: Padding(
        padding: EdgeInsets.all(8),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              height: 120,
              color: Colors.grey[200],
              alignment: Alignment.center,
              child: Text('商品图片', style: TextStyle(color: Colors.grey)),
            ),
            SizedBox(height: 8),
            Text(
              name,
              style: TextStyle(fontSize: 12),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
            SizedBox(height: 4),
            Text(promo, style: TextStyle(color: Colors.red, fontSize: 10)),
            SizedBox(height: 4),
            Row(
              children: [
                Text('￥$price',
                    style: TextStyle(color: Colors.red, fontSize: 16)),
                Spacer(),
                Text('销量999+',
                    style: TextStyle(color: Colors.grey, fontSize: 10)),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCheckoutBar(double total, int selectedCount) {
    return Container(
      height: 50,
      color: Colors.white,
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: Row(
        children: [
          Row(
            children: [
              Checkbox(
                activeColor: Colors.red,
                value: _selectAll,
                shape: CircleBorder(),
                onChanged: (value) {
                  setState(() {
                    _selectAll = value!;
                    _cartItems = _cartItems.map((item) {
                      return item.copyWith(selected: value);
                    }).toList();
                  });
                },
              ),
              Text('全选'),
            ],
          ),
          Spacer(),
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Text('共$selectedCount件商品', style: TextStyle(fontSize: 12)),
              Text('总计￥${total.toStringAsFixed(1)}',
                  style: TextStyle(color: Colors.red, fontSize: 16)),
            ],
          ),
          SizedBox(width: 16),
          ElevatedButton(
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20),
              ),
              padding: EdgeInsets.symmetric(horizontal: 24, vertical: 10),
            ),
            onPressed: () {},
            child: Text('去结算', style: TextStyle(color: Colors.white)),
          ),
        ],
      ),
    );
  }
}

class cartData {
  late final String name;
  late final String desc;
  late final String originalPrice;
  late final String price;
}

class CartItem {
  String name;
  String size;
  String packages;
  double price;
  int count;
  bool selected;
  String img;

  CartItem(
      {required this.name,
      required this.size,
      required this.packages,
      required this.price,
      required this.count,
      required this.selected,
      required this.img});
      

  // 从 Map 转换为 CartItem
  factory CartItem.fromMap(Map<String, dynamic> map) {
    return CartItem(
      name: map['name'] ?? '默认商品',
      size: map['size'] ?? '20',
      packages: map['packages'] ?? "",
      price: double.tryParse(map['price'].substring(1)) ?? 11.0,
      count: map['count'] ?? 1,
      selected: map['selected'] ?? false,
      img: map['img'] ?? '',
    );
  }

  // 转换为 Map
  Map<String, dynamic> toMap() {
    return {
      'name': name,
      'size': size,
      'packages': packages,
      'price': price,
      'count': count,
      'selected': selected,
    };
  }

  CartItem copyWith({
    String? name,
    String? size,
    String? packages,
    double? price,
    int? count,
    bool? selected,
    String? img,
  }) {
    return CartItem(
      name: name ?? this.name,
      size: size ?? this.size,
      packages: packages ?? this.packages,
      price: price ?? this.price,
      count: count ?? this.count,
      selected: selected ?? this.selected,
      img: img ?? this.img,
    );
  }
  
}
